package com.ruoyi.quartz.task;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.BusInsomniaAlert;
import com.ruoyi.system.domain.BusSleepRecord;
import com.ruoyi.system.service.IBusInsomniaAlertService;
import com.ruoyi.system.service.IBusSleepRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * 失眠预警定时任务
 * 每天凌晨 3 点执行一次
 */
@Component("insomniaTask")
public class InsomniaTask {

    @Autowired
    private IBusSleepRecordService sleepRecordService;

    @Autowired
    private IBusInsomniaAlertService insomniaAlertService;

    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HHmm");

    /**
     * 检查昨天的睡眠数据，生成失眠预警
     */
    public void checkYesterdaySleep() {
        System.out.println("=== 开始执行失眠预警定时任务 ===");

        // 获取昨天日期（只保留年月日）
        LocalDate yesterday = LocalDate.now().minusDays(1);

        BusSleepRecord query = new BusSleepRecord();
        query.setRecordDate(java.sql.Date.valueOf(yesterday));

        // 查询昨天的所有睡眠记录
        List<BusSleepRecord> records = sleepRecordService.selectBusSleepRecordList(query);

        for (BusSleepRecord record : records) {
            Long userId = record.getUserId();
            Long recordId = record.getId();
            Double duration = record.getSleepDuration(); // 分钟数

            // ========== 规则 1：睡眠不足 ==========
            if (duration != null && duration < 6) { // 6 小时 = 360 分钟
                insertAlert(userId, recordId, "睡眠不足", "昨晚睡眠时长少于 6 小时，请注意休息！", "2");
            }

            // ========== 规则 2：晚起 ==========
            if (StringUtils.isNotEmpty(record.getWakeTime())) {
                try {
                    LocalTime wakeTime = LocalTime.parse(record.getWakeTime(), TIME_FORMATTER);
                    if (wakeTime.isAfter(LocalTime.of(8, 00))) {
                        insertAlert(userId, recordId, "晚起", "起床时间晚于 8 点，可能存在睡眠紊乱。", "1");
                    }
                } catch (Exception e) {
                    System.err.println("WakeTime 转换失败：" + record.getWakeTime());
                }
            }

            // ========== 规则 2b：晚睡 ==========
            if (StringUtils.isNotEmpty(record.getBedTime())) {
                try {
                    LocalTime bedTime = LocalTime.parse(record.getBedTime(), TIME_FORMATTER);
                    if (bedTime.isAfter(LocalTime.of(00, 30))) {
                        insertAlert(userId, recordId, "晚睡", "入睡时间晚于 00:30，可能存在晚睡习惯。", "1");
                    }
                } catch (Exception e) {
                    System.err.println("BedTime 转换失败：" + record.getBedTime());
                }
            }

            // ========== 规则 3：补偿行为 ==========
            if ("1".equals(record.getCompensationBehavior())) {
                insertAlert(userId, recordId, "补偿行为", "存在补偿性睡眠行为。", "1");
            }

            // ========== 规则 4：缺乏运动 ==========
            if ("1".equals(record.getLackOfExercise())) {
                insertAlert(userId, recordId, "缺乏运动", "昨日缺乏运动，可能影响睡眠质量。", "1");
            }

            // ========== 规则 5：强迫入睡 ==========
            if ("1".equals(record.getForcedSleep())) {
                insertAlert(userId, recordId, "强迫入睡", "存在努力入睡或强迫性入睡行为。", "2");
            }
        }

        System.out.println("=== 失眠预警定时任务执行完毕 ===");
    }

    /**
     * 插入一条预警记录
     */
    private void insertAlert(Long userId, Long recordId, String alertType, String message, String level) {
        BusInsomniaAlert alert = new BusInsomniaAlert();
        alert.setUserId(userId);
        alert.setRecordId(recordId.intValue());
        alert.setAlertType(alertType);
        alert.setAlertMessage(message);
        alert.setAlertLevel(level);
        alert.setCreateTime(new Date());

        insomniaAlertService.insertBusInsomniaAlert(alert);

        System.out.println(StringUtils.format("新增失眠预警：用户{}，类型{}，等级{}，提示：{}", userId, alertType, level, message));
    }
}
